package com.example.thirdstage_project.filter;



import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;



//@WebFilter("/*")
public class MyFilter implements Filter {
    //不需要登录就可以访问的路径(比如:登录等)
     private String[] includeUrls = new String[]{"/index.html","/jieshao.html","/lianxi.html","/login.html","/zhinan.html"};


    public void destroy() {
    }

    public void init(FilterConfig config) throws ServletException {

    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        HttpSession session = request.getSession();

        String uri = request.getRequestURI();

//是否需要过滤
        boolean needFilter = isNeedFilter(uri);

        if (!needFilter) { //不需要过滤直接传给下一个过滤器
            chain.doFilter(req, resp);
        } else { //需要过滤器
            // session中包含user对象,则是登录状态
            if (session != null && session.getAttribute("user") != null) {
                // System.out.println("user:"+session.getAttribute("user"));
                chain.doFilter(request, response);
            } else {
                //重定向到登录页
                response.sendRedirect(request.getContextPath() + "/login.html");
            }
            return;
        }

    }


    public boolean isNeedFilter(String uri) {

        for (String includeUrl : includeUrls) {
            if (includeUrl.equals(uri)) {
                return false;
            }
        }

        return true;
    }

}

